package com.keda.springdata_elasticsearch.listener;

import com.keda.springdata_elasticsearch.config.LogConfigPropertires;
import com.keda.springdata_elasticsearch.exception.LogCodeMessage;
import com.keda.springdata_elasticsearch.repositories.OperationLogDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Slf4j
@ConditionalOnMissingClass
@Component
public class AutoCreateLogIndex {

    @Autowired
    private LogConfigPropertires logConfigPropertires;

    @Autowired(required = false)
    private OperationLogDao operationLogDao;

    /**
     * 容器启动成功，检查索引
     */
    @EventListener
    public void createLogIndex() {
        //会议操作记录
        try {
            boolean exist = operationLogDao.existIndex();
            if (!exist) {
                operationLogDao.createIndex();
                log.info("create log index {} success", logConfigPropertires.getEs().getIndexName());
            } else {
                log.info("index {} has existed", logConfigPropertires.getEs().getIndexName());
            }
        } catch (Exception e) {
            log.error(LogCodeMessage.ELOG101.getMessage());
        }
        //错误消息记录
        try {
            boolean exist = operationLogDao.existErrorLogIndex();
            if (!exist) {
                operationLogDao.createErrorLogIndex();
                log.info("create error log index {} success", logConfigPropertires.getEs().getErrorLogIndexName());
            } else {
                log.info("index {} has existed", logConfigPropertires.getEs().getErrorLogIndexName());
            }
        } catch (Exception e) {
            log.error(LogCodeMessage.ELOG101.getMessage());
        }
        //日志管理
        try {
            boolean exist = operationLogDao.existDispatchLogIndex();
            if (!exist) {
                operationLogDao.createDispatchLogIndex();
                log.info("create dispatch log index {} success", logConfigPropertires.getEs().getDispatchLogIndexName());
            } else {
                log.info("index {} has existed", logConfigPropertires.getEs().getDispatchLogIndexName());
            }
        } catch (Exception e) {
            log.error(LogCodeMessage.ELOG101.getMessage());
        }


    }
}
